package cn.tedu.bonfire.admin.account.service.impl;


import cn.tedu.bonfire.admin.account.dao.cache.IUserCacheRepository;
import cn.tedu.bonfire.admin.account.dao.persist.repository.IUserRepository;
import cn.tedu.bonfire.admin.account.pojo.dto.UserAddNewDTO;
import cn.tedu.bonfire.admin.account.pojo.entity.User;
import cn.tedu.bonfire.admin.account.pojo.entity.UserAndRole;
import cn.tedu.bonfire.admin.account.pojo.vo.UserManagementVO;
import cn.tedu.bonfire.admin.account.service.INoteService;
import cn.tedu.bonfire.admin.account.service.IUserAndRoleService;
import cn.tedu.bonfire.admin.account.service.IUserRoleService;
import cn.tedu.bonfire.admin.account.service.IUserService;
import cn.tedu.bonfire.common.enumerator.ServiceCode;
import cn.tedu.bonfire.common.ex.ServiceException;
import cn.tedu.bonfire.common.pojo.po.UserAdminSearchPO;
import cn.tedu.bonfire.common.pojo.po.UserCachePO;
import cn.tedu.bonfire.common.pojo.po.UserStatePO;
import cn.tedu.bonfire.common.pojo.vo.PageData;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import java.io.IOException;
import java.util.List;

import static cn.tedu.bonfire.common.consts.data.changeContsts.*;

@Service
public class UserServiceImpl implements IUserService {



    @Autowired
    private IUserCacheRepository userCacheRepository;
    @Value("${bonfire.dao.default-query-page-size}")
    private Integer defaultQueryPageSize;
    @Autowired
    private IUserRepository userRepository;
    @Autowired
    private PasswordEncoder passwordEncoder;
    @Autowired
    private IUserAndRoleService userAndRoleService;
    @Autowired
    private IUserRoleService userRoleService;
    @Autowired
    private INoteService noteService;

    @Override
    public void addNew(UserAddNewDTO userAddNewDTO) {
        {
            String username = userAddNewDTO.getUsername();
            Long count = userRepository.countByUserName(username);
            if (count > 0) {
                String message = "添加用户失败，用户名已经被占用";
                throw new ServiceException(ServiceCode.ERROR_CONFLICT, message);
            }
        }

        {
            String phone = userAddNewDTO.getPhone();
            Long count = userRepository.countByPhone(phone);
            if (count>0){
                String message = "添加用户失败，手机号码已经被占用！";
                throw new ServiceException(ServiceCode.ERROR_CONFLICT, message);
            }
        }

        Long roleId = userAddNewDTO.getRoleId();
        String roleName = userRoleService.selectRoleNameById(roleId);

        User user=new User();
        BeanUtils.copyProperties(userAddNewDTO,user);
        //TODO 默认头像
        String password = user.getPassword();
        String encodedPassword = passwordEncoder.encode(password);
        user.setPassword(encodedPassword);
        user.setEnable(user.getEnable());
        user.setDescription(roleName);
        int rows = userRepository.insert(user);
        if (rows != 1) {
            String message = "注册失败，服务器忙，请稍后再尝试！";
            throw new ServiceException(ServiceCode.ERROR_INSERT, message);
        }

        Long userId = user.getId();

        /*插入关联表*/
        UserAndRole userAndRole = new UserAndRole();

        userAndRole.setUserId(userId);
        userAndRole.setRoleId(userAddNewDTO.getRoleId());
        userAndRoleService.insert(userAndRole);


    }



    @Override
    public void deleteByUserId(Long userId, Integer enable) {
        User user=new User();
        int delete1 = userRepository.deleteByUserId(userId,enable);
        if (userId==null){
            String message = "用户获取失败，服务器忙，请稍后再尝试！";
            throw new ServiceException(ServiceCode.ERROR_UPDATE, message);
        }
        user.setEnable(2);

        List<Long> noteIdList = noteService.selectNoteById(userId);
        if (noteIdList==null){
            return;
        }
        for (Long noteId: noteIdList) {
            noteService.deleteNoteStatus(noteId,1);
        }
    }

    /**
     *  * 分页查询
     * @param pageNum
     * @return
     */
    @Override
    public PageData<UserManagementVO> list(Integer pageNum) {
        PageData<UserManagementVO> list = userRepository.list(pageNum, defaultQueryPageSize);
        return userRepository.list(pageNum,defaultQueryPageSize);
    }

    @Override
    public void updateNickname(Long userId,String nickname) {
        if(userId==null){
            String message = "用户获取失败，服务器忙，请稍后再尝试！";
            throw new ServiceException(ServiceCode.ERROR_UPDATE, message);
        }

        User user = new User();
        user.setId(user.getId());
        int rows = userRepository.updateNicknameByUserId(userId,nickname);
        if (rows != 1) {
            String message = "修改昵称失败，服务器忙，请稍后再尝试！";
            throw new ServiceException(ServiceCode.ERROR_UPDATE, message);
        }
    }

    @Override
    public void updateAvatar(Long userId, String avatar) {
        int rows =userRepository.updateAvatarByUserId(userId,avatar);
        if (rows!=1){
            String message = "修改昵称失败，服务器忙，请稍后再尝试！";
            throw new ServiceException(ServiceCode.ERROR_UPDATE, message);
        }
    }

    @Override
    public void setEnable(Long userId) {
        updateEnableById(userId,ENABLE_STATE_ON);
    }

    @Override
    public void setDisable(Long userId) {
        updateEnableById(userId, ENABLE_STATE_OFF);
    }





    /**
     *     * 修改用户的启用状态
     * @param id
     * @param enable
     */
    private void updateEnableById(Long id, Integer enable) {
        if (id == 1) {
            String message = ENABLE_STATE_TEXT[enable] + "用户失败，尝试访问的数据不存在！";
            throw new ServiceException(ServiceCode.ERROR_NOT_FOUND, message);
        }
        User user = new User();
        user.setId(id);
        user.setEnable(enable);
        int rows = userRepository.updateById(user);
        if (rows != 1) {
            String message = ENABLE_STATE_TEXT[enable] + "用户失败，服务器忙，请稍后再次尝试！";
            throw new ServiceException(ServiceCode.ERROR_UPDATE, message);
        }

        if (enable.equals(ENABLE_STATE_OFF)) {
            UserCachePO userState = userCacheRepository.getUserState(id);
            if (userState != null) {
                userCacheRepository.setUserDisabled(id);
            }
        }

    }



}
